package middle;

public class Solution_148 {

    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode slow = head, fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode two = sortList(slow.next);
        slow.next = null;
        ListNode one = sortList(head);
        return merge(one, two);
    }

    public ListNode merge(ListNode one, ListNode two) {
        if (one == null) {
            return two;
        } else if (two == null) {
            return one;
        } else {
            ListNode rst;
            if (one.val <= two.val) {
                rst = one;
                one = one.next;
            } else {
                rst = two;
                two = two.next;
            }
            rst.next = merge(one, two);
            return rst;
        }
    }

    public static void main(String[] args) {
        Solution_148 model = new Solution_148();
        ListNode head = new ListNode(4);
        head.next = new ListNode(2);
        head.next.next = new ListNode(1);
        head.next.next.next = new ListNode(3);
        head.next.next.next = new ListNode(0);
        ListNode rst = model.sortList(head);
        System.out.println();
    }

    static class ListNode {

        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
